package cn.javaex.hgo.action.system.service.hgo_role_info;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.javaex.hgo.action.system.dao.hgo_role_info.IHgoRoleInfoDAO;
import cn.javaex.hgo.action.system.dao.hgo_role_menu.IHgoRoleMenuDAO;
import cn.javaex.hgo.action.system.view.HgoRoleInfo;
import cn.javaex.hgo.config.constant.HgoErrorMsg;
import cn.javaex.hgo.config.exception.HgoException;

@Service("HgoRoleInfoService")
public class HgoRoleInfoService {
	
	@Autowired
	private IHgoRoleInfoDAO iHgoRoleInfoDAO;
	@Autowired
	private IHgoRoleMenuDAO iHgoRoleMenuDAO;
	
	/**
	 * 查询所有角色
	 * @return
	 */
	public List<HgoRoleInfo> list() {
		return iHgoRoleInfoDAO.list();
	}

	/**
	 * 根据主键查询角色
	 * @param id 角色id
	 * @return
	 */
	public HgoRoleInfo selectById(String id) {
		return iHgoRoleInfoDAO.selectById(id);
	}
	
	/**
	 * 查询目前最大排序
	 * @return
	 */
	public int selectMaxSort() {
		int maxSort = 0;
		try {
			maxSort = iHgoRoleInfoDAO.selectMaxSort();
		} catch (Exception e) {
			
		}
		return maxSort;
	}
	
	/**
	 * 保存角色
	 * @param hgoRoleInfo
	 * @throws HgoException
	 */
	public void save(HgoRoleInfo hgoRoleInfo) throws HgoException {
		// 1.0 角色标识是否重复
		int count = iHgoRoleInfoDAO.countByCode(hgoRoleInfo.getCode(), hgoRoleInfo.getId());
		if (count>0) {
			throw new HgoException(HgoErrorMsg.ERROR_100011);
		}
		
		// 2.0 新增或更新
		if (StringUtils.isEmpty(hgoRoleInfo.getId())) {
			// 新增
			iHgoRoleInfoDAO.insert(hgoRoleInfo);
		} else {
			// 更新
			iHgoRoleInfoDAO.update(hgoRoleInfo);
		}
	}

	/**
	 * 删除角色
	 * @param id 角色id
	 */
	public void deleteById(String id) {
		// 1.0 删除角色-菜单的分配
		iHgoRoleMenuDAO.deleteByRoleId(id);
		
		// 2.0 删除角色
		iHgoRoleInfoDAO.deleteById(id);
	}

}